package com.example.bikemanagerjava.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bikemanagerjava.common.Result;
import com.example.bikemanagerjava.entity.Bike;
import com.example.bikemanagerjava.service.impl.BikeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin("*")
public class BikeController {

    @Autowired
    private BikeServiceImpl bikeService;

    @PostMapping("/bikes")
    public Result addBike(@RequestBody Bike bike) {

        bikeService.save(bike); //插入 bike 数据

        return Result.success();
    }

    @GetMapping("/bikes")
    public Result getBikes(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam String bikenumber,
                           @RequestParam String status) {
        QueryWrapper<Bike> queryWrapper = new QueryWrapper<Bike>().orderByDesc("id");
        queryWrapper.like(StrUtil.isNotBlank(status), "status", status);
        queryWrapper.like(StrUtil.isNotBlank(bikenumber),"bikenumber", bikenumber);
        Page<Bike> page = bikeService.page(new Page<>(pageNum, pageSize), queryWrapper); //分页查询
        return Result.success(page);
    }

    @GetMapping("/bikes/{id}")
    public Result getBike(@PathVariable Integer id) {

        Bike bike = bikeService.getById(id); //根据 id 查询单车信息

        return Result.success(bike);
    }

    @DeleteMapping("/bikes/{id}")
    public Result deleBike(@PathVariable Integer id) {

        bikeService.removeById(id);

        return Result.success();
    }

    @PutMapping("/bikes")
    public Result putBike(@RequestBody Bike bike) {

        bikeService.updateById(bike);

        return Result.success();
    }

}
